﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.DAL;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.Devices;
using HamcoWcs.Models.Exceptions;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace HamcoWcs.Service.Pcon.PconPlcDbMsgParsers
{
    public class PconMsgParse_ArriveReport : PconMsgParseBase
    {
        private readonly ILoggerService _loggerService;
        private readonly IBaseTaskService _baseTaskService;
        public override EnumPconPlcRequest RequestType => EnumPconPlcRequest.ArriveReport;

        public PconMsgParse_ArriveReport(IMapper mapper, WcsDbContext wcsDbContext,
            IBaseTaskService baseTaskService, ILoggerService loggerService)
            : base(null, wcsDbContext, mapper)
        {
            _baseTaskService = baseTaskService;
            _loggerService = loggerService;
        }
        public override void Deal(PconDto pconDto, PconPlc pconPlc)
        {

            if (string.IsNullOrEmpty(pconDto.UnitId))
            {
                return;
            }

            var taskEntity = _wcsDbContext.SubTasks.AsQueryable()
                                                   .Where(x => x.TaskStatus == EnumSubTaskStatus.OnProgress.ToString())
                                                   .Where(x => x.UnitId == pconDto.UnitId)
                                                   .Where(x => x.ToLoc == pconDto.MachineName)
                                                   .Include(x => x.MainTask)
                                                   .FirstOrDefault();

            if (taskEntity == null)
            {
                taskEntity = _wcsDbContext.SubTasks.AsQueryable()
                                                   .Where(x => x.TaskStatus == EnumSubTaskStatus.Ready.ToString())
                                                   .Where(x => x.UnitId == pconDto.UnitId)
                                                   .Where(x => x.ToLoc == pconDto.MachineName)
                                                   .Include(x => x.MainTask)
                                                   .FirstOrDefault();
            }


            if (taskEntity == null)
                return;

            if (pconDto.PconType != EnumPconType.Wharf1 && taskEntity == null)
            {
                _loggerService.AddWcsRunLog(pconDto.UnitId, $"{pconDto.Machine}-{pconDto.PortName}到达，任务表中无正在执行的托盘号为{pconDto.UnitId}的任务");
            }



            var res = _baseTaskService.UpdateSubTaskStatus(taskEntity.Id, EnumSubTaskStatus.Finished);


            if (!res)
            {
                throw new WarningException("修改任务状态异常");
            }
            //if (pconDto.PconType == EnumPconType.OutPortInteractive)
            //{
            //    // 二楼出库口需要上报 退Port完成
            //    pconDto.PortState = "LC";
            //    _mesCommunicateService.PortTransferStateChanged(pconDto);
            //}

        }
    }
}
